﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class admin_module_form_user : System.Web.UI.UserControl
{
    UserBus userbus = new UserBus();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            loadData();
        }
    }
    public void loadData()
    {
        int user_id = 0;
        gender.Items.Add(new ListItem("Nam", "true"));
        gender.Items.Add(new ListItem("Nu", "false"));
        getUsergroup();
        User user = new User();
        if (Request.QueryString["user_id"] != null && Request.QueryString["user_id"] != "")
        {
            user_id = Convert.ToInt32(Request.QueryString["user_id"]);
            user = userbus.getUserByID(user_id);            
        }
        this.setData(user);
        
    }
    public void getUsergroup()
    {
        user_groupBus usergroupbus = new user_groupBus();
        DataTable dt = usergroupbus.getAllUserGroup();
        foreach (DataRow r in dt.Rows)
        {
            listusergroup.Items.Add(new ListItem(r["name"].ToString(), r["user_group_id"].ToString()));
        }
    }
    public void setData(User user)
    {
        username.Text = user.User_name;
        password.Text = user.Password.Trim();
        fullname.Text = user.FullName;
        email.Text = user.Email;
        re_email.Text = user.Email;
        birthday.SelectedDate = user.Birthday;
        gender.SelectedValue = user.Sex.ToString();
        address.Text = user.Address;
        phone.Text = user.Phone;
        listusergroup.SelectedValue = user.User_group_id.ToString();
    }

    protected void Cancel_User_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("default.aspx?action=user");

    }
    protected void OK_User_Click(object sender, ImageClickEventArgs e)
    {
        int user_id = 0;
        if (Request.QueryString["user_id"] != null && Request.QueryString["user_id"] != "")
        {
            user_id = Convert.ToInt32(Request.QueryString["user_id"]);
        }
        string passMD5 = userbus.MaHoaMD5(password.Text.Trim());
        User user = new User(
                 user_id,
                 username.Text.Trim(),
                 passMD5,
                 fullname.Text.Trim(),
                 birthday.SelectedDate,
                 email.Text.Trim(),
                 Convert.ToBoolean(gender.SelectedValue),
                 address.Text.Trim(),
                 phone.Text.Trim(),
                 Convert.ToInt32(listusergroup.SelectedValue),
                 DateTime.Now
            );
        if (userbus.Insert_UpdateUser(user))
        {
            Response.Redirect("default.aspx?action=user");
        }
    }
}